<?php

/**
 * 订单分析
 *
 * @author haifeng.wu
 */

require_once 'CommonController.php';
class Admin_ActivationAnalyticsController extends Admin_CommonController
{
    /**
     * 初始化函数
     * 
     * @return void
     */
    public function init()
    {
        parent::init();
        $this->_model = new Application_Model_DayData();
        $this->dayAreaDataModel = new Application_Model_DayAreaData();
        $this->sourceModel = new Application_Model_Source();
        $this->memberModel = new Application_Model_Member();
        $this->conversionModel = new Application_Model_ActDayDataConversion();
        $this->view->title = "管理中心";
    }

    /**
     * 默认动作
     * 
     * @return void
     */
    public function listAction()
    {
        $vars = array();
        $wheres = array();
        $vars['dateType'] = trim($this->_request->get('dateType')) ? trim($this->_request->get('dateType')) : 6;
        $vars['doType'] = trim($this->_request->get('doType')) ? trim($this->_request->get('doType')) : 1;
        $vars['startTime'] = trim($this->_request->get('startTime'));
        $vars['endTime'] = trim($this->_request->get('endTime'));
        $vars['export'] = trim($this->_request->get('export'))!='' ? trim($this->_request->get('export')) : 'no';
        if ($vars['dateType']==6){
            $vars['startTime'] = date('Y-m-d',strtotime("now"));
            $vars['endTime']   = date('Y-m-d',strtotime("now"));
        } elseif ($vars['dateType']==1){
            $vars['startTime'] = date('Y-m-d',strtotime("-1 day"));
            $vars['endTime']   = date('Y-m-d',strtotime("-1 day"));
        } elseif ($vars['dateType']==2){
            $vars['startTime'] = date('Y-m-d',strtotime("-8 day"));
            $vars['endTime']   = date('Y-m-d',strtotime("-1 day"));
        } elseif ($vars['dateType']==3){
            $vars['startTime'] = date('Y-m-d',strtotime("-31 day"));
            $vars['endTime']   = date('Y-m-d',strtotime("-1 day"));
        } elseif ($vars['dateType']==4){
            $vars['startTime'] = date('Y-m-d',strtotime("-3 months"));
            $vars['endTime']   = date('Y-m-d',strtotime("-1 day"));
        } elseif ($vars['dateType']==5){
            $vars['startTime'] = '';
            $vars['endTime']   = '';
        }
        
        $this->view->vars = $vars;
        $productCode = Application_Model_UserLogin::getInstance()->getUserCurrentProductCode();
        $wheres[] = "s.productCode = '{$productCode}'";
        
        if ($vars['startTime'] != '') {
            $wheres[] = " s.date >= '{$vars['startTime']}' ";
        }
        if ($vars['endTime'] != '') {
            $wheres[] = " s.date <= '{$vars['endTime']}' ";
        }
        $where = count($wheres) > 0 ? ' WHERE ' . implode(' AND ', $wheres) . ' ' : '';
        $group = '';
        if ($vars['doType'] == 3) {//操作系统分析
            $group = " GROUP BY s.osName ";
            $sql = "SELECT s.osName AS name,sum(s.installNum) AS installNum,sum(s.installOkOrderAmount) AS amount,sum(s.installOkOrderNum) AS installOkOrderNum
             FROM " . $this->_model->getTableName() . " AS s " . $where . $group;
            $row = $this->_model->getAdapter()->fetchAll($sql);
            $rowAmount = 0;
            foreach ($row as $item) {
                $rowAmount += $item['amount'];
            }
            $tmpArray = array();
            $tmpArray = $rowAmount == 0 ? $row : sysSortArray($row,'installNum',$SortOrder1 = "SORT_DESC",$SortType1 = "SORT_REGULAR");
            
            $amountTotal = 0;
            $installOkOrderNumTotal = 0;
            $installNumTotal = 0;

            foreach ($tmpArray as $key => $val) {
                if (empty($val['name'])) {
                    $tmpArray[$key]['name'] = '未知';
                }
                $installNumTotal += $val['installNum'];
                $amountTotal += $val['amount'];
                $installOkOrderNumTotal += $val['installOkOrderNum'];
            }

            //总计数据
            $totalArray = array('installNumTotal' => $installNumTotal, 'amountTotal' => number_format($amountTotal, 2), 'installOkOrderNumTotal' => $installOkOrderNumTotal);
            if ($totalArray['installNumTotal'] == 0) {
                $totalArray['installNumTotalPer'] = '--';
            } else {
                $totalArray['installNumTotalPer'] = '100%';
            }
            if ($totalArray['installOkOrderNumTotal'] == 0) {
                $totalArray['installOkOrderNumTotalPer'] = '--';
            } else {
                $totalArray['installOkOrderNumTotalPer'] = '100%';
            }

            //计算占比
            foreach ($tmpArray as $key => $val) {
                $tmpArray[$key]['installNumPer'] = $installNumTotal == 0 ? 0 : round($val['installNum']/$installNumTotal ,4) * 100;
                $tmpArray[$key]['installOkOrderNumPer'] = $installOkOrderNumTotal == 0 ? 0 : round($val['installOkOrderNum']/$installOkOrderNumTotal, 4) * 100;
                $tmpArray[$key]['amountPer'] = $amountTotal == 0 ? 0 : round($val['amount']/$amountTotal, 2) * 100;
            }

            //金额占比小于百分之一数据的计算
            $endArray = array('name' => '其他', 'installNum' =>0, 'amount' => 0, 'installNumPer' => 0, 'amountPer' => 0 , 'installOkOrderNum' => 0, 'installOkOrderNumPer' => 0 );
            foreach ($tmpArray as $key => $val) {
                if ($val['installNumPer'] < 0) {
                    $endArray['amount'] += $val['amount'];
                    $endArray['installNum'] += $val['installNum'];
                    $endArray['installOkOrderNum'] += $val['installOkOrderNum'];
                    unset($tmpArray[$key]);
                }
            }
            if ($endArray['installNum'] != 0) {
                $endArray['installNumPer'] = $installNumTotal == 0 ? 0 : round($endArray['installNum']/$installNumTotal ,4) * 100;
                $endArray['installOkOrderNumPer'] = $installOkOrderNumTotal == 0 ? 0 : round($endArray['installOkOrderNum']/$installOkOrderNumTotal, 4) * 100;
                $tmpArray[] = $endArray;
            }
            
            foreach ($tmpArray as $key => $val) {
                $tmpArray[$key]['amount'] = number_format($val['amount'] ,2);
                if ($tmpArray[$key]['installNumPer'] >= 100) {
                    $tmpArray[$key]['installNumPer'] = 100;
                }
            }
            $this->view->totalArray = $totalArray;
            $this->view->tmpArray = $tmpArray;
            if($vars['export'] == 'yes'){
                $exportArray = array();
                $exportArray['name'] = '总计';
                $exportArray['installNum'] = $totalArray['installNumTotal'];
                $exportArray['amount'] = $totalArray['amountTotal'];
                $exportArray['installOkOrderNum'] = $totalArray['installOkOrderNumTotal'];
                $exportArray['installNumPer'] = $totalArray['installNumTotalPer'];
                $exportArray['installOkOrderNumPer'] = $totalArray['installOkOrderNumTotalPer'];
                $tmpArray[] = $exportArray;
                $resArray = array();
                $exportNum =1;
                foreach ($tmpArray as $item) {
                    $exportNum++;
                    $resArray['A'.$exportNum]= $item['name'];
                    $resArray['B'.$exportNum]= $item['installNum'];
                    $resArray['C'.$exportNum]= $item['installNumPer'];
                    $resArray['D'.$exportNum]= $item['installOkOrderNum'];
                    $resArray['E'.$exportNum]= $item['installOkOrderNumPer'];
                    $resArray['F'.$exportNum]= $item['amount'];
                }
                $table = array();
                $table[0]['tableName'] = '激活量-按操作系统';
                $table[0]['title'] = array('操作系统','激活数量','激活占比(%)','激活带来的订单量','激活带来的订单占比','激活带来的订单金额');
                $table[0]['con'] = $resArray;
                $this->conversionModel->excelExport($table,"[{$vars['startTime']}_{$vars['endTime']}]{$productCode}-export");
            }
        } else if($vars['doType'] == 4) {
            $group = " GROUP BY s.province ";
            $sql = "SELECT s.province AS name,sum(s.installNum) AS installNum,sum(s.installOkOrderAmount) AS amount,sum(s.installOkOrderNum) AS installOkOrderNum
             FROM " . $this->dayAreaDataModel->getTableName() . " AS s " . $where . $group;
            $row = $this->_model->getAdapter()->fetchAll($sql);
            $rowAmount = 0;
            foreach ($row as $item) {
                $rowAmount += $item['amount'];
            }
            $tmpArray = array();
            $tmpArray = $rowAmount == 0 ? $row : sysSortArray($row,'installNum',$SortOrder1 = "SORT_DESC",$SortType1 = "SORT_REGULAR");
            
            $amountTotal = 0;
            $installOkOrderNumTotal = 0;
            $installNumTotal = 0;

            foreach ($tmpArray as $key => $val) {
                if (empty($val['name']) || $val['name'] == '其他') {
                    $tmpArray[$key]['name'] = '国外';
                }
                $installNumTotal += $val['installNum'];
                $amountTotal += $val['amount'];
                $installOkOrderNumTotal += $val['installOkOrderNum'];
            }

            //总计数据
            $totalArray = array('installNumTotal' => $installNumTotal, 'amountTotal' => number_format($amountTotal, 2), 'installOkOrderNumTotal' => $installOkOrderNumTotal);
            if ($totalArray['installNumTotal'] == 0) {
                $totalArray['installNumTotalPer'] = '--';
            } else {
                $totalArray['installNumTotalPer'] = '100%';
            }
            if ($totalArray['installOkOrderNumTotal'] == 0) {
                $totalArray['installOkOrderNumTotalPer'] = '--';
            } else {
                $totalArray['installOkOrderNumTotalPer'] = '100%';
            }

            //计算占比
            foreach ($tmpArray as $key => $val) {
                $tmpArray[$key]['installNumPer'] = $installNumTotal == 0 ? 0 : round($val['installNum']/$installNumTotal ,4) * 100;
                $tmpArray[$key]['installOkOrderNumPer'] = $installOkOrderNumTotal == 0 ? 0 : round($val['installOkOrderNum']/$installOkOrderNumTotal, 4) * 100;
                $tmpArray[$key]['amountPer'] = $amountTotal == 0 ? 0 : round($val['amount']/$amountTotal, 2) * 100;
                if ($val['amount'] == 0 && $val['installNum'] == 0 && $val['installOkOrderNum'] == 0) {
                    unset($tmpArray[$key]);
                }
            }

            foreach ($tmpArray as $key => $val) {
                $tmpArray[$key]['amount'] = number_format($val['amount'] ,2);
                if ($tmpArray[$key]['installNumPer'] >= 100) {
                    $tmpArray[$key]['installNumPer'] = 100;
                }
            }
            $this->view->totalArray = $totalArray;
            $this->view->tmpArray = $tmpArray;
            if($vars['export'] == 'yes'){
                $exportArray = array();
                $exportArray['name'] = '总计';
                $exportArray['installNum'] = $totalArray['installNumTotal'];
                $exportArray['amount'] = $totalArray['amountTotal'];
                $exportArray['installOkOrderNum'] = $totalArray['installOkOrderNumTotal'];
                $exportArray['installNumPer'] = $totalArray['installNumTotalPer'];
                $exportArray['installOkOrderNumPer'] = $totalArray['installOkOrderNumTotalPer'];
                $tmpArray[] = $exportArray;
                $resArray = array();
                $exportNum =1;
                foreach ($tmpArray as $item) {
                    $exportNum++;
                    $resArray['A'.$exportNum]= $item['name'];
                    $resArray['B'.$exportNum]= $item['installNum'];
                    $resArray['C'.$exportNum]= $item['installNumPer'];
                    $resArray['D'.$exportNum]= $item['installOkOrderNum'];
                    $resArray['E'.$exportNum]= $item['installOkOrderNumPer'];
                    $resArray['F'.$exportNum]= $item['amount'];
                }
                $table = array();
                $table[0]['tableName'] = '激活量-按地区';
                $table[0]['title'] = array('地区','激活数量','激活占比(%)','激活带来的订单量','激活带来的订单占比','激活带来的订单金额');
                $table[0]['con'] = $resArray;
                $this->conversionModel->excelExport($table,"[{$vars['startTime']}_{$vars['endTime']}]{$productCode}-export");
            }
        } else {
            $group = " GROUP BY m.code ";
            $sql = "SELECT m.code,m.name,s.sourceId,s.sourceSubId,s.productCode,sum(s.installNum) AS installNum,sum(s.installOkOrderAmount) AS amount,sum(s.installOkOrderNum)
             AS installOkOrderNum 
            FROM " . $this->_model->getTableName() . " AS s LEFT JOIN " . $this->sourceModel->getTableName() .
             " AS u ON s.productCode = u.productCode AND s.sourceId = u.sourceId AND s.sourceSubId = u.sourceSubId LEFT JOIN " .
            $this->memberModel->getTableName() . " AS m ON u.memberCode = m.code " . $where . $group;
            $row = $this->_model->getAdapter()->fetchAll($sql);
            $rowAmount = 0;
            foreach ($row as $item) {
                $rowAmount += $item['amount'];
            }
            $tmpArray = array();
            $tmpArray = $rowAmount == 0 ? $row : sysSortArray($row,'installNum',$SortOrder1 = "SORT_DESC",$SortType1 = "SORT_REGULAR");
            
            $amountTotal = 0;
            $installOkOrderNumTotal = 0;
            $installNumTotal = 0;

            foreach ($tmpArray as $key => $val) {
                if (empty($val['name'])) {
                    $tmpArray[$key]['name'] = '未知';
                }
                $installNumTotal += $val['installNum'];
                $amountTotal += $val['amount'];
                $installOkOrderNumTotal += $val['installOkOrderNum'];
            }

            //总计数据
            $totalArray = array('installNumTotal' => $installNumTotal, 'amountTotal' => number_format($amountTotal, 2), 'installOkOrderNumTotal' => $installOkOrderNumTotal);
            if ($totalArray['installNumTotal'] == 0) {
                $totalArray['installNumTotalPer'] = '--';
            } else {
                $totalArray['installNumTotalPer'] = '100%';
            }
            if ($totalArray['installOkOrderNumTotal'] == 0) {
                $totalArray['installOkOrderNumTotalPer'] = '--';
            } else {
                $totalArray['installOkOrderNumTotalPer'] = '100%';
            }

            //计算占比
            foreach ($tmpArray as $key => $val) {
                $tmpArray[$key]['installNumPer'] = $installNumTotal == 0 ? 0 : round($val['installNum']/$installNumTotal ,4) * 100;
                $tmpArray[$key]['installOkOrderNumPer'] = $installOkOrderNumTotal == 0 ? 0 : round($val['installOkOrderNum']/$installOkOrderNumTotal, 4) * 100;
                $tmpArray[$key]['amountPer'] = $amountTotal == 0 ? 0 : round($val['amount']/$amountTotal, 2) * 100;
            }
            //金额占比小于百分之一数据的计算
            $endArray = array('code' => 'other', 'name' => '其他', 'installNum' =>0, 'amount' => 0, 'installNumPer' => 0, 'amountPer' => 0 , 'installOkOrderNum' => 0, 'installOkOrderNumPer' => 0, 'strCode' => '');
            $arrayCode = array();
            foreach ($tmpArray as $key => $val) {
                if ($val['installNumPer'] < 0) {
                    $endArray['amount'] += $val['amount'];
                    $endArray['installNum'] += $val['installNum'];
                    $endArray['installOkOrderNum'] += $val['installOkOrderNum'];
                    $arrayCode[] = $val['code'];
                    unset($tmpArray[$key]);
                }
            }
            if ($endArray['installNum'] != 0) {
                $endArray['installNumPer'] = $installNumTotal == 0 ? 0 : round($endArray['installNum']/$installNumTotal ,4) * 100;
                $endArray['installOkOrderNumPer'] = $installOkOrderNumTotal == 0 ? 0 : round($endArray['installOkOrderNum']/$installOkOrderNumTotal, 4) * 100;
                $endArray['strCode'] = implode(',', $arrayCode);
                $tmpArray[] = $endArray;
            }
            
            foreach ($tmpArray as $key => $val) {
                $tmpArray[$key]['amount'] = number_format($val['amount'] ,2);
                if ($tmpArray[$key]['installNumPer'] >= 100) {
                    $tmpArray[$key]['installNumPer'] = 100;
                }
            }
            $this->view->totalArray = $totalArray;
            $this->view->tmpArray = $tmpArray;
            if($vars['export'] == 'yes'){
                $exportArray = array();
                $exportArray['name'] = '总计';
                $exportArray['installNum'] = $totalArray['installNumTotal'];
                $exportArray['amount'] = $totalArray['amountTotal'];
                $exportArray['installOkOrderNum'] = $totalArray['installOkOrderNumTotal'];
                $exportArray['installNumPer'] = $totalArray['installNumTotalPer'];
                $exportArray['installOkOrderNumPer'] = $totalArray['installOkOrderNumTotalPer'];
                $tmpArray[] = $exportArray;
                $resArray = array();
                $exportNum =1;
                foreach ($tmpArray as $item) {
                    $exportNum++;
                    $resArray['A'.$exportNum]= $item['name'];
                    $resArray['B'.$exportNum]= $item['installNum'];
                    $resArray['C'.$exportNum]= $item['installNumPer'];
                    $resArray['D'.$exportNum]= $item['installOkOrderNum'];
                    $resArray['E'.$exportNum]= $item['installOkOrderNumPer'];
                    $resArray['F'.$exportNum]= $item['amount'];
                }
                $table = array();
                $table[0]['tableName'] = '激活量-按渠道';
                $table[0]['title'] = array('渠道','激活数量','激活占比(%)','激活带来的订单量','激活带来的订单占比','激活带来的订单金额');
                $table[0]['con'] = $resArray;
                $this->conversionModel->excelExport($table,"[{$vars['startTime']}_{$vars['endTime']}]{$productCode}-export");
            }
        }
    }

    /**
    * 获取软件包
    * @return void
    */
    function getSourceNameListAction(){
        $productCode = Application_Model_UserLogin::getInstance()->getUserCurrentProductCode();
        $name = trim($this->_request->getPost('name'));
        $startTime = trim($this->_request->getPost('startTime'));
        $strCode = trim($this->_request->getPost('strCode'));
        if (empty($startTime)) {
            $startTime = 0;
        }
        $endTime = trim($this->_request->getPost('endTime'));
        if (empty($endTime)) {
            $endTime = date('Y-m-d');
        }
        if (!empty($strCode)) {
            $tmpCode = array();
            $tmpCode = explode(',', $strCode);
            $type = 1;
            if (in_array('', $tmpCode)) {
                $type = 0;
            }
            $strCode = "'" . str_replace(",", "','", $strCode) . "'";
            $where = '';
            if ($type == 1) {
                $where .= " AND c.code in (" . $strCode . ") ";
            } else {
                $where .= " AND ( c.code in (" . $strCode . ") or c.name IS NULL )";
            }
        } else {
            $where = '';
            if ($name == '未知') {
                $where .= " AND c.name IS NULL ";
            } else {
                $where .= " AND c.name = '{$name}' ";
            }

        }
        $sql = "SELECT b.sourceName as sourceName,a.sourceId,a.sourceSubId,c.name,sum(a.installNum) as installNum,sum(a.installOkOrderNum) as installOkOrderNum,sum(a.installOkOrderAmount) as amount 
        FROM mob_day_data AS a  
        LEFT JOIN mob_source AS b ON a.productCode = b.productCode AND a.sourceId = b.sourceId AND a.sourceSubId = b.sourceSubId
        LEFT JOIN mob_member AS c ON b.memberCode = c.code 
        WHERE a.date>='{$startTime}' AND a.date<='{$endTime}' AND a.productCode = '{$productCode}' AND installNum != 0 " . $where . " 
        GROUP BY a.sourceId,a.sourceSubId 
        ORDER BY installNum DESC ";
        $row = $this->_model->getAdapter()->fetchAll($sql);
        $tmpArray = array();
        $amountTotal = 0;
        $installOkOrderNumTotal = 0;
        $installNumTotal = 0;

        foreach ($row as $key => $val) {
            $installNumTotal += $val['installNum'];
            $amountTotal += $val['amount'];
            $installOkOrderNumTotal += $val['installOkOrderNum'];
        }
        //计算占比
        foreach ($row as $key => $val) {
                $row[$key]['installNumPer'] = $installNumTotal == 0 ? 0 : round($val['installNum']/$installNumTotal ,4) * 100;
                $row[$key]['installOkOrderNumPer'] = $installOkOrderNumTotal == 0 ? 0 : round($val['installOkOrderNum']/$installOkOrderNumTotal, 4) * 100;
                $row[$key]['amountPer'] = $amountTotal == 0 ? 0 : round($val['amount']/$amountTotal, 2) * 100;
        }
        $table = '<tr class="subject">
                    <td>子渠道</td>
                    <td colspan="2">激活</td>
                    <td colspan="3">激活用户</td>
                  </tr>
                  <tr class="subject">
                    <td>名称</td>
                    <td>数量</td>
                    <td>占比(%)</td>
                    <td>订单量</td>
                    <td>占比(%)</td>
                    <td>订单金额(￥)</td>
                  </tr>';
        foreach ($row as $item) {
            $table .= '
                      <tr>
                        <td>' . $item["sourceName"] . '</td>
                        <td>' . $item["installNum"] . '</td>
                        <td>' . $item["installNumPer"] . '</td>
                        <td>' . $item["installOkOrderNum"] . '</td>
                        <td>' . $item["installOkOrderNumPer"] . '</td>
                        <td>' . $item["amount"] . '</td>
                      </tr>
            ';
        }
        echo json_encode(array('table' => $table));
        exit;
    }
    
    
}